package file

import (
	"bufio"
	"bytes"
	"encoding/hex"
	"fmt"
	"os"
	"path"
	"strconv"
	"strings"
)

// 创建文件并写入内容
func Writer(path string, context ...string) {
	noCreate(path)
	file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		fmt.Printf("open file merror=%v\n", err)
		return
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	for i := 0; i < len(context); i++ {
		writer.WriteString(context[i] + "\t")
	}
	writer.WriteString("\r\n\r\n")
	writer.Flush()
}

func noCreate(path string) {
	catalogue := getCatalogue(path)
	_, exist := os.Stat(catalogue)
	if os.IsNotExist(exist) {
		os.MkdirAll(catalogue, os.ModePerm)
	}
}

func getCatalogue(path string) string {
	res := ""
	desPath := strings.Split(path, "/")
	for i := 0; i < len(desPath)-1; i++ {
		res += desPath[i] + "/"
	}
	return res
}

var picMap map[string]string

func init() {
	picMap = make(map[string]string)
	picMap["ffd8ffe0"] = "jpg"
	picMap["ffd8ffe1"] = "jpg"
	picMap["ffd8ffe8"] = "jpg"
	picMap["89504e47"] = "png"
	picMap["47494638"] = "gif"
	picMap["49492A00"] = "tif"
	picMap["424DC001"] = "bmp"
	picMap["41433130"] = "dwg"
	picMap["38425053"] = "psd"
	picMap["7B5C727466"] = "rtf"
	picMap["3C3F786D6C"] = "xml"
	picMap["68746D6C3E"] = "html"
	picMap["44656C69766572792D646174653A"] = "eml"
	picMap["CFAD12FEC5FD746F"] = "dbx"
	picMap["2142444E"] = "pst"
	picMap["D0CF11E0"] = "doc"
	picMap["5374616E64617264204A"] = "mdb"
	picMap["FF575043"] = "wpd"
	picMap["255044462D312E"] = "pdf"
	picMap["AC9EBD8F"] = "qdf"
	picMap["E3828596"] = "pwl"
	picMap["504B0304"] = "zip"
	picMap["52617221"] = "rar"
	picMap["57415645"] = "wav"
	picMap["41564920"] = "avi"
	picMap["2E7261FD"] = "ram"
	picMap["2E524D46"] = "rm"
	picMap["000001BA"] = "mpg"
	picMap["000001B3"] = "mpg"
	picMap["6D6F6F76"] = "mov"
	picMap["3026B2758E66CF11"] = "asf"
	picMap["4D546864"] = "mid"

}

// 判断文件头是否和文件后缀匹配
func Verify(file *os.File) bool {
	buf := make([]byte, 20)
	n, _ := file.Read(buf)
	fileNameWithSuffix := path.Base(file.Name())
	//获取文件的后缀(文件类型)
	fileType := strings.ToLower(path.Ext(fileNameWithSuffix))[1:]
	switch fileType {
	case "jpeg":
		fileType = "jpg"
	case "tiff":
		fileType = "tif"
	case "cad":
		fileType = "dwg"
	case "xls":
		fileType = "doc"
	case "mpeg":
		fileType = "mpg"
	case "wave":
		fileType = "wav"

	}
	fileCode := bytesToHexString(buf[:n])
	for k, v := range picMap {
		if strings.HasPrefix(fileCode, k) {
			return v == fileType
		}
	}
	return false
}

//获取16进制
func bytesToHexString(src []byte) string {
	res := bytes.Buffer{}
	if src == nil || len(src) <= 0 {
		return ""
	}
	temp := make([]byte, 0)
	i, length := 100, len(src)
	if length < i {
		i = length
	}
	for j := 0; j < i; j++ {
		sub := src[j] & 0xFF
		hv := hex.EncodeToString(append(temp, sub))
		if len(hv) < 2 {
			res.WriteString(strconv.FormatInt(int64(0), 10))
		}
		res.WriteString(hv)
	}
	return res.String()
}
